/**
 * @description: 复制指令
 * @example: <div v-copy="content">复制</div>
 * @example: <div v-copy>复制的内容</div>
 */
import { message } from 'ant-design-vue'

export default {
  beforeMount(el, binding) {
    if (!binding.value) return
    el.targetContent = binding.value
    //添加hover样式
    el.style.cursor = 'pointer'
    el.addEventListener('click', () => {
      if (!el.targetContent) return console.warn('没有需要复制的目标内容')
      const textarea = document.createElement('textarea')
      textarea.readOnly = 'readonly'
      textarea.style.position = 'fixed'
      textarea.style.top = '-99999px'
      textarea.value = el.targetContent
      document.body.appendChild(textarea)
      textarea.select()
      const res = document.execCommand('Copy')
      const messageText = el.targetContent.length > 10 ? '内容已复制到剪切板' : `【${el.targetContent} 】已复制到剪切板`
      res && message.success(messageText)
      document.body.removeChild(textarea)
    })
  },
  updated(el, binding) {
    if (!binding.value) return
    el.targetContent = binding.value
  },
  unmounted(el) {
    el.removeEventListener('click', () => ({}))
  }
}
